import os
from sqlite3 import Connection
from datetime import datetime, timedelta
from services.server_integration.schemas.full_unit_configuration import FullUnitConfiguration


def startup_patch_12_10_23(model):
    """enable ac_link_rx, ac_link_tx, acc_base_power_calibrate, acc_link_calibrate"""
    fuc = model.full_unit_config
    fuc.unit_configuration.ac_link_rx = True
    fuc.unit_configuration.ac_link_tx = True
    fuc.unit_configuration.acc_base_power_calibrate = True
    fuc.unit_configuration.acc_link_calibrate = True

    model.save_only_full_config(fuc)


def startup_patch_19_10_23(model):
    """enable ac_link_rx, ac_link_tx, ac_service_tx, acc_base_power_calibrate, acc_link_calibrate, acc_tx_service_calibrate"""
    fuc = model.full_unit_config
    fuc.unit_configuration.ac_link_rx = True
    fuc.unit_configuration.ac_link_tx = True
    fuc.unit_configuration.ac_service_tx = True
    fuc.unit_configuration.acc_base_power_calibrate = True
    fuc.unit_configuration.acc_link_calibrate = True
    fuc.unit_configuration.acc_tx_service_calibrate = True

    model.save_only_full_config(fuc)


def start_up_patch_11_12_23(model):
    fuc = model.full_unit_config
    serial_number: str = fuc.unit_configuration.main_module.serial_number
    fuc.unit_configuration.cviya = 'ЦВИЯ.464117.' + serial_number.split(' ')[0]
    model.save_only_full_config(fuc)


async def start_up_patch_set_unit_config_by_technic(model):
    from services.new_services.technic_page.schemas.technic_configuration import TechnicConfiguration
    from services.new_services.technic_page.api import TechnicPageApi
    fuc: FullUnitConfiguration = model.full_unit_config

    serial_number = fuc.unit_configuration.main_module.serial_number
    api = TechnicPageApi()
    await api.set_unit_config_by_technic(
        TechnicConfiguration(
            cviya='ЦВИЯ.464117.' + serial_number.split(' ')[0],
            serial_number=serial_number,
            block_ip=str(fuc.unit_configuration.device.ip),
            mac_address=fuc.unit_configuration.main_module.mac_address,
            ac_link_tx=fuc.unit_configuration.ac_link_tx,
            ac_link_rx=fuc.unit_configuration.ac_link_rx,
            ac_service_tx=fuc.unit_configuration.ac_service_tx,
            acc_base_power_calibrate=fuc.unit_configuration.acc_base_power_calibrate,
            acc_link_calibrate=fuc.unit_configuration.acc_link_calibrate,
            acc_tx_service_calibrate=fuc.unit_configuration.acc_tx_service_calibrate,
        ),
        'adjuster'
    )


def clean_alarms_10_04_24(connection: Connection):
    start_data = int(datetime(2024, 3, 26).timestamp())
    delete_delta = int(timedelta(hours=1).total_seconds())

    sql = f'DELETE FROM ALARMS_LOG WHERE ALARMS_LOG.time < {start_data} OR (ALARMS_LOG.end_time - ALARMS_LOG.time) < {delete_delta}'
    connection.cursor().execute(sql)
    connection.commit()

def update_updater():
    """update_updater 1.0.6"""
    import os
    from common.third_party.update_updater import update_updater
    update_updater()
    os.system('systemctl stop rcs-updater.service')
    os.system('systemctl start rcs-updater.service')


def update_wdialirz_daemon():
    """update wdialirz"""
    import os
    from common.third_party.update_updater import update_wdialirz
    os.system('systemctl stop wdialirz.service')
    update_wdialirz()
    os.system('systemctl start wdialirz.service')


def update_wtelitncm_daemon():
    """update wtelitncm"""
    import os
    from common.third_party.update_updater import update_wtelitncm
    os.system('systemctl stop wtelitncm.service')
    update_wtelitncm()
    os.system('systemctl start wtelitncm.service')


def enable_old_frontend():
    import os
    os.system('systemctl enable rcs-frontend.service')
    os.system('systemctl start rcs-frontend.service')

def remote_link_dl_tx_pack():
    import os
    try:
        os.system('rm /home/debian/rcs/environment/dma/link-dl-tx')
    except:
        pass

def update_linux():
    import os
    os.system('dd if=/home/debian/rcs/software/radius_control_backend/common/image5.ub of=/dev/mtdblock4 bs=64K')
    os.system('dd if=/home/debian/rcs/software/radius_control_backend/common/syst5.dtb of=/dev/mtdblock5 bs=64K')
    os.system('dd if=/home/debian/rcs/software/radius_control_backend/common/design_1_w1806.bin of=/dev/mtdblock0 bs=64K')

def reboot_power_patch():
    import os, asyncio
    async def reboot():
        await asyncio.sleep(66)
        os.system('echo -e "\xAA\xBB\xCC\x03" > /dev/ttyUL3')

    asyncio.create_task(reboot())

def reboot_patch():
    import os, asyncio
    async def reboot():
        await asyncio.sleep(66)
        os.system('reboot')

    asyncio.create_task(reboot())

def disable_garbage_services():
    try:
        os.system('systemctl disable rcs-new-frontend.service')
    except Exception:
        pass

    try:
        os.system('systemctl disable rcs-debug-12.service')
    except Exception:
        pass

def yog_sothoth_systemd_log_fix():
    try:
        os.system('sh /home/debian/rcs/software/radius_control_backend/common/third_party/yog-sothoth-systemd-log-fix.sh')
    except Exception:
        pass


def update_kintex():
    try:
        os.system("dd if=/home/debian/rcs/software/radius_control_backend/common/third_party/design_300_pss_v10.bin of=/dev/mtdblock0 bs=64K")
    except Exception:
        pass
